//
//  ILFashionWebViewController.m
//  ILife
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILFashionWebViewController.h"
#import "ILDetailWebView.h"
#import <AFHTTPRequestOperationManager.h>
#import "ILFashionDetailBasonModel.h"
#import "MJRefresh.h"
#import "FMDatabase.h"
@interface ILFashionWebViewController ()<UIWebViewDelegate,UIScrollViewDelegate,UITabBarControllerDelegate>
@property (nonatomic, strong) ILDetailWebView *ILDWebView;
@property (nonatomic, strong) ILFashionDetailBasonModel *detailModel;
@property (nonatomic, assign) CGFloat webHeight;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, assign) CGFloat changy;
@property (nonatomic, copy) NSString *titleNext;
@property (nonatomic, copy) NSString *titleLast;
@property (nonatomic, strong) MJRefreshGifHeader *headerNext;
@property (nonatomic, strong) MJRefreshAutoGifFooter *headerLast;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, copy) NSString *isCollect;// 是否被收藏
@property (nonatomic, copy) NSString *collectTitle;// 收藏的标题
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) UIAlertView *alert;


@end

@implementation ILFashionWebViewController

- (NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray == nil) {
        self.dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}
-(NSMutableArray *)titleArray
{
    if (_titleArray == nil) {
        self.titleArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _titleArray;
}


// 页面将要消失的时候 关闭
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.hidesBarsOnSwipe = NO;

}





- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.isCollect = @"no";
    
    
    _ILDWebView = [[ILDetailWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
    _ILDWebView.scrollView.delegate = self;
    
    _ILDWebView.opaque = NO;
    
    _ILDWebView.backgroundColor = [UIColor clearColor];
    
    _detailModel = [[ILFashionDetailBasonModel alloc]init];
    
    self.navigationController.hidesBarsOnSwipe = YES;
    
    
    [self.view addSubview:_ILDWebView];
    
    
    [self requestData];
    
    // 创建数据库/打开数据库
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"ILArticCollcet.db"];
    

    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    //[_dataBase executeUpdate:@"drop table artic"];
    
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        // 创建表格
        [_dataBase executeUpdate:@"create table artic(contentid text, thumb text, title text, isCollect text, Artfrom text, home_contentid text)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }

    
    
}




// 点击收藏按钮的事件
- (void)collect:(UIButton *)button
{
   
    
    // 判断是否被收藏
    if ([self.isCollect isEqualToString:@"no"]) {
        
        
        [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];

        
            

        if ([_detailModel.title isEqualToString: @"nul"] && [_detailModel.title isEqualToString:@""]) {

            return;
        }
        else
        {
            self.isCollect = @"yes";
        [_dataBase executeUpdate:@"insert into artic(contentid, thumb, title, isCollect, Artfrom, home_contentid) values(?,?,?,?,?,?)",self.contentid, _detailModel.thumb, _detailModel.title, self.isCollect, self.from, self.home_contentid];
        
        _alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_alert show];
        
        self.isCollect = @"yes";
        }
    }
    else
    {
        _alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏了，换一个吧。" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_alert show];
    }
    
}

//alert 自动消失
-(void) performDismiss:(NSTimer *)timer
{
    [_alert dismissWithClickedButtonIndex:0 animated:NO];
}



- (void) requestData
{
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    
    // AFNetWork2.0以上要添加下面的话
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    
    NSString *str = @"http://app.ellemen.com/?app=rss&controller=elleplus&action=elleplus_content";
    NSString *lastStr = [NSString stringWithFormat:@"&contentid=%@&from=%@&home_contentid=%@",self.contentid,self.from,self.home_contentid];
    
    NSString *urlStr = [str stringByAppendingString:lastStr];
    
    [manger GET:urlStr parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
            [_dataSourceArray removeAllObjects];
            [_detailModel setValuesForKeysWithDictionary:responseObject[@"data"]];
        
            // 刷新webView
            [self.ILDWebView reload];
            
            // 加载webView
            [self requestWebView];
            
        // 收藏按钮
        
        [self.rightButton removeFromSuperview];
        _rightButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _rightButton.frame = CGRectMake(0, 0, 30, 30);
        
        
        FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from artic"];
        
            while ([resultSet next]) {
                
                _collectTitle = [resultSet stringForColumn:@"title"];
                self.isCollect = [resultSet stringForColumn:@"isCollect"];
                
                // 将数据库中的标题存入数组
                [self.titleArray addObject:_collectTitle];
                
            }
            [resultSet close];
            
            for (NSString *title in _titleArray) {
                
                // 判断是否为收藏的文章
                if ([_detailModel.title isEqualToString:title])
                {
                    [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];
                    self.isCollect = @"yes";
                    // 如果有相同的就跳出循环
                    break;
                }
                else
                {
                    [_rightButton setImage:[UIImage imageNamed:@"collect"] forState:(UIControlStateNormal)];
                    self.isCollect = @"no";
                }
            }
        

        if ([self.isCollect isEqualToString:@"yes"]) {
            [_rightButton setImage:[UIImage imageNamed:@"collected"] forState:(UIControlStateNormal)];
        }
        else{
            [_rightButton setImage:[UIImage imageNamed:@"collect"] forState:(UIControlStateNormal)];
        }
        [_rightButton addTarget:self action:@selector(collect:) forControlEvents:(UIControlEventTouchUpInside)];
        UIBarButtonItem* rightBtnItem = [[UIBarButtonItem alloc]initWithCustomView:_rightButton];
        [self.navigationItem setRightBarButtonItem:rightBtnItem];

        
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];

}





- (void)requestWebView
{

    [_ILDWebView loadHTMLString:_detailModel.body_html baseURL:nil];
     _ILDWebView.delegate = self;
    self.navigationController.navigationBarHidden = NO;
    
}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    self.webHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    CGFloat changeY = self.ILDWebView.scrollView.contentOffset.y;
    CGFloat diffValue = changeY - _changy;
    _changy = changeY;
    
    
    // 当相对滑动距离大于0时 隐藏
    if (diffValue > 0.0) {

        [UIView animateWithDuration:0.5 animations:^{
           
            self.tabBarController.tabBar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, self.tabBarController.tabBar.bounds.size.height);
        }];
    }
    
    // 当相对滑动小于0时 显示
    if (diffValue < 0.0)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.tabBarController.tabBar.frame = CGRectMake(0, SCREEN_HEIGHT - self.tabBarController.tabBar.bounds.size.height , SCREEN_WIDTH, self.tabBarController.tabBar.bounds.size.height);
        }];
    }
    
    // 滑到最后时 显示
    if (changeY+SCREEN_HEIGHT  >= self.webHeight-100) {
        [UIView animateWithDuration:0.5 animations:^{
            self.tabBarController.tabBar.frame = CGRectMake(0, SCREEN_HEIGHT - self.tabBarController.tabBar.bounds.size.height , SCREEN_WIDTH, self.tabBarController.tabBar.bounds.size.height);
        }];
        self.navigationController.navigationBarHidden = NO;

    }
    
    // 滑到最前面时 显示
    if (changeY <= -64.0 ) {
        [UIView animateWithDuration:0.5 animations:^{
            self.tabBarController.tabBar.frame = CGRectMake(0, SCREEN_HEIGHT - self.tabBarController.tabBar.bounds.size.height , SCREEN_WIDTH, self.tabBarController.tabBar.bounds.size.height);
        }];
        self.navigationController.navigationBarHidden = NO;
    }
    

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
